package org.devops

//封装HTTP请求
//credentialsId是jenkins中凭据类型为secret text的gitlab api token产生的id
/*
注意事项:
    如果写为credentialsId: "gitlab_api_token"，构建时会报错Error when executing failure post condition:
        org.jenkinsci.plugins.credentialsbinding.impl.CredentialNotFoundException: Credentials 'gitlab_api_token' is of type 'GitLab Personal Access Token' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected
    在多方查询过后，发现这其实是gitlab plugin 在处理Credential时候的一个bug，
        至今无人修复， Feature: Support Jenkins Credentials for "Secret Token" #494， https://github.com/jenkinsci/gitlab-plugin/issues/494
        所以根据ticket中的描述， workaround 的方法是,将这个token添加为简单的jenkins secret text, that will works

解决方法:
    就是将gitlab的api token在jenkins中以secret text类型保存为凭据即可使用
*/
def HttpReq(reqType,reqUrl,reqBody){
    def gitServer = "http://192.168.56.120:8880/api/v4"
    withCredentials([string(credentialsId: '667a7f94-1ee2-4b54-9075-88c0f82f74fc', variable: 'gitlab_api_token')]) {
      result = httpRequest customHeaders: [[maskValue: true, name: 'PRIVATE-TOKEN', value: "${gitlab_api_token}"]], 
                httpMode: reqType, 
                contentType: "APPLICATION_JSON",
                consoleLogResponseBody: true,
                ignoreSslErrors: true, 
                requestBody: reqBody,
                url: "${gitServer}/${reqUrl}"
                //quiet: true
    }
    return result
}

//获取项目ID
def GetProjectID(repoName='',projectName){
    projectApi="projects?search=${projectName}"
    response=HttpReq('GET',projectApi,'')
    def result=readJSON text: """${response.content}"""
    for (repo in result){
        if (repo['path']=="${projectName}"){
            repoId=repo['id']
            println(repoId)
        }
    }
    return repoId
}

//更改提交状态
def ChangeCommitStatus(projectId,commitSha,status){
    commitApi = "projects/${projectId}/statuses/${commitSha}?state=${status}"
    response = HttpReq('POST',commitApi,'')
    println(response)
    return response
}
